/*
 * @Description:
 * @Version: 2.0
 * @Autor: jl.g
 * @Date: 2022-08-18 13:59:22
 * @LastEditors: jl.g
 * @LastEditTime: 2023-08-21 09:13:24
 */
import React, { useRef, useEffect, useState } from "react";
import { Layout, Dropdown, Space, Menu, notification } from "antd";
import { DownOutlined, InfoCircleOutlined } from "@ant-design/icons";
import Marquee from "react-fast-marquee";
import styles from "./index.module.less";
import UserDetail from "./components/UserDetail";
import { useHistory } from "react-router-dom";
import { getUserInfo, getNavList, productConsumedTypeConfig } from "@/api/user";
import { systemConfig } from "@/api/login";

import WaveCanvas from "../WaveCanvas";
import {
  userInfoAction,
  createSysConfig,
  consumptionPromptAction,
  setMenuDataListAction,
  setActiveMenuItemKey,
  systemThemAction,
} from "@/store/actions/home_action";
import {
  geneartMenu,
  isMobileDevice,
  setSessionStorage,
  getSessionStorage,
  getLocalStorage,
  setLocalStorage,
} from "@/utils";
import { useDispatch } from "react-redux";
import InviteGiftUrlInfo from "@/components/InviteGiftUrlInfo";
import FreeQuestion from "./components/FreeQuestion";
import userDeafultImg from "../../../public/assets/imgs/userDeafultImg.svg";
import JoinGroup from "./components/JoinGroup";
import horn from "../../../public/assets/imgs/horn.svg";
import sysVipFlag from "../../../public/assets/imgs/sysVipFlag.svg";
import sysVipFlagFail from "../../../public/assets/imgs/sysVipFlagFail.svg";
import "./shake.css";
const { Header } = Layout;

const HeadComponent = (props) => {
  const dispatch = useDispatch();
  const history = useHistory();
  const userDetailRef = useRef(null);
  const [userInfo, setUserInfo] = useState(null);
  const inviteGiftUrlInfoRef = useRef(null);
  const freeQuestionRef = useRef(null);
  const joinGroupRef = useRef(null);
  const [navList, setNavList] = useState([]);
  // 系统配置
  const [sysConfig, setSysConfig] = useState({});

  // 判断移动端还是pc
  // true 移动端
  // false pc
  const deviceType = useRef(isMobileDevice());

  useEffect(() => {
    getUserInfoFn();

    systemConfigFn();

    getNavListFn();

    // getProductConsumedTypeConfig();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 获取商品消耗提示
  const getProductConsumedTypeConfig = async () => {
    try {
      let res = await productConsumedTypeConfig();
      if (res.code === 200) {
        dispatch(consumptionPromptAction(res.result));
      }
    } catch (error) {
      console.log(error);
    }
  };

  // 获取系统配置
  const systemConfigFn = async () => {
    try {
      let res = await systemConfig();
      if (res.code === 200) {
        let resData = res.result;
        setSysConfig(resData);
        dispatch(createSysConfig(resData));
        setSessionStorage("sysConfig", JSON.stringify(resData));
        let activeMenuItemKey = getSessionStorage("activeMenuItemKey");
        // 根据后台设置的菜单id,获取菜单列表
        if (resData.leftMenuIds && resData.leftMenuIds.length) {
          let generateMenuList = geneartMenu(resData.leftMenuIds);
          // 将菜单存储到store
          dispatch(setMenuDataListAction(generateMenuList));

          // 初始化菜单选中
          if (!activeMenuItemKey) {
            dispatch(setActiveMenuItemKey(resData.leftMenuIds[0]));
            setSessionStorage("activeMenuItemKey", resData.leftMenuIds[0]);
            history.replace(generateMenuList[0].path);
          } else {
            dispatch(setActiveMenuItemKey(activeMenuItemKey));
          }
        }

        // 设置网站主题
        // 如果用户自己没设置过则设置为网站默认的
        let localSysTheme = getLocalStorage("theme");
        if (!localSysTheme) {
          setLocalStorage("theme", resData.sysTheme);
          document.body.setAttribute("theme-mode", resData.sysTheme);
          // 设置全局主题
          dispatch(systemThemAction(resData.sysTheme));
        } else {
          document.body.setAttribute("theme-mode", localSysTheme);
          dispatch(systemThemAction(localSysTheme));
        }

        // 设置网站图标
        var link =
          document.querySelector("link[rel*='icon']") ||
          document.createElement("link");

        link.type = "image/x-icon";

        link.rel = "shortcut icon";

        link.href = resData?.iconUrl || "";

        document.getElementsByTagName("head")[0].appendChild(link);
        document.title = resData.webName;

        // 设置平台提示语

        if (resData.indexPopup) {
          notification.open({
            duration: null,
            icon: <InfoCircleOutlined style={{ color: "#108ee9" }} />,
            message: "尊敬的用户您好",
            description: (
              <div
                dangerouslySetInnerHTML={{
                  __html: resData.indexPopup,
                }}
              ></div>
            ),
          });
        }
        // notification
      }
    } catch (error) {
      console.log(error);
    }
  };

  /**
   * @description: 获取用户详情
   * @return {*}
   * @author: jl.g
   */
  const getUserDetail = () => {
    userDetailRef.current.getPage();
  };

  /**
   * @description: 获取用户信息
   * @return {*}
   * @author: jl.g
   */

  const getUserInfoFn = async () => {
    try {
      let res = await getUserInfo();
      if (res.code === 200) {
        let resData = res.result;
        setUserInfo(resData);
        dispatch(userInfoAction(resData));
      } else {
        dispatch(userInfoAction(null));
      }
    } catch (error) {
      console.log(error);
    }
  };

  /**
   * @description: 购买vip
   * @return {*}
   * @author: jl.g
   */
  const buyVip = () => {
    history.replace("/ai/commodity");
  };

  // 获取导航列表
  const getNavListFn = async () => {
    try {
      let res = await getNavList();
      if (res.code === 200) {
        setNavList(res.result || []);
      }
    } catch (error) {
      console.log(error);
    }
  };
  // 自定义弹窗
  const customDialog = (data) => {
    if (data.buttonType === 10) {
      joinGroupRef.current.getPage(data);
    } else {
      window.open(data.jumpUrl);
    }
  };

  // 跳转首页
  const backUpHome = () => {
    console.log(sysConfig, "sysConfig");
    let homeUrl = window.location.origin;
    window.location.href = homeUrl;
  };
  return (
    <>
      <Header className={styles.header}>
        {/* 移动端不需要展示 */}
        {!deviceType.current ? <WaveCanvas></WaveCanvas> : ""}

        <div className="headr_content">
          <div className="logoBox" onClick={backUpHome}>
            {sysConfig?.iconUrl ? (
              <img className="logo" src={sysConfig?.iconUrl} alt="" />
            ) : (
              ""
            )}

            <p className="title">{sysConfig.webName}</p>
          </div>

          {sysConfig.announcement ? (
            <div className="marquee_warp ">
              <img className="marquee_warp-horn" src={horn} alt="" />
              <Marquee pauseOnHover={true} speed={30} loop={0}>
                <div className="info">{sysConfig.announcement}</div>
              </Marquee>
            </div>
          ) : (
            ""
          )}

          <div className="userInfo">
            {/* 超过4个展示更多福利做成下拉 */}
            {navList.length > 4 ? (
              <Dropdown
                className="propose"
                overlay={
                  <Menu>
                    {navList.map((v) => (
                      <Menu.Item key={v.id} onClick={() => customDialog(v)}>
                        {v.buttonName}
                      </Menu.Item>
                    ))}
                  </Menu>
                }
                trigger={["click"]}
              >
                <Space>
                  <a
                    className="ant-dropdown-link"
                    onClick={(e) => e.preventDefault()}
                  >
                    更多福利
                    <DownOutlined />
                  </a>
                </Space>
              </Dropdown>
            ) : (
              navList.map((v) => (
                <div
                  key={v.id}
                  onClick={() => customDialog(v)}
                  className="propose"
                >
                  {v.buttonName}
                </div>
              ))
            )}

            {/* {navList.map((v) => (
              <div
                key={v.id}
                onClick={() => customDialog(v)}
                className="propose"
              >
                {v.buttonName}
              </div>
            ))} */}

            {/*<div onClick={buyVip} className="bug_vip">*/}
            {/*  购买会员*/}
            {/*</div>*/}

            <div className="user_info-box" onClick={getUserDetail}>
              <div className="user_avatar-box">
                {userInfo?.memberFlag ? (
                  <img className="sysVipFlag" src={sysVipFlag} alt="" />
                ) : (
                  <img className="sysVipFlag" src={sysVipFlagFail} alt="" />
                )}

                <img
                  className="user_avatar"
                  src={userInfo?.headImgUrl || userDeafultImg}
                  alt=""
                />
              </div>

              <span className="userName">
                {userInfo?.nikeName ||
                  `游客 ${(Math.random() * 1000).toFixed(0)}`}
              </span>
            </div>
          </div>

          <div className="mobile_userInfo">
            <div className="mobile_userInfo-warp">
              {/* 如果没有配置导航则不进行展示 */}
              {navList.length ? (
                <Dropdown
                  className="propose"
                  overlay={
                    <Menu>
                      {navList.map((v) => (
                        <Menu.Item key={v.id} onClick={() => customDialog(v)}>
                          {v.buttonName}
                        </Menu.Item>
                      ))}
                    </Menu>
                  }
                  trigger={["click"]}
                >
                  <Space>
                    <a
                      className="ant-dropdown-link"
                      onClick={(e) => e.preventDefault()}
                    >
                      更多福利
                      <DownOutlined />
                    </a>
                  </Space>
                </Dropdown>
              ) : (
                ""
              )}

              <div onClick={buyVip} className="bug_vip">
                购买
              </div>

              <div className="user_info-box">
                <img
                  onClick={getUserDetail}
                  className="user_avatar"
                  src={userInfo?.headImgUrl || userDeafultImg}
                  alt=""
                />
              </div>
            </div>
          </div>
        </div>
      </Header>

      {/* 用户信息 */}
      <UserDetail ref={userDetailRef}></UserDetail>

      {/* 邀请返利 */}
      <InviteGiftUrlInfo ref={inviteGiftUrlInfoRef}></InviteGiftUrlInfo>

      {/* 免费领取次数 */}
      <FreeQuestion ref={freeQuestionRef}></FreeQuestion>

      {/* 加入我们 */}
      <JoinGroup ref={joinGroupRef} />
    </>
  );
};

export default HeadComponent;
